import com.chen.common.util.time.TimeUtil;

import java.util.concurrent.*;

/**
 * @author ex_chenzy59
 * @since 2025/2/26
 * 虚拟线程的使用
 */
public class 虚拟线程 {
    public final static int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    /**
     * 得到虚拟线程池
     */
    public static ThreadPoolExecutor getVirtualExecutor(int maxThreadSize) {
        int keepAliveTime = 30;//空闲线程存活时间
        int coreSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));//核心线程数
        int maxSize = Math.max(maxThreadSize,Math.max(CPU_COUNT * 2 + 1,5000));//最大线程数
        System.out.println("coreSize:"+coreSize);
        System.out.println("CPU_COUNT:"+CPU_COUNT);
        System.out.println("最大线程数:"+maxSize);

        return new ThreadPoolExecutor(coreSize,maxSize,keepAliveTime, TimeUnit.SECONDS,new LinkedBlockingQueue<>(1)
                ,Thread.ofVirtual().factory()
                , new ThreadPoolExecutor.DiscardPolicy()//丢弃新任务
        );
    }
    private static void processTask(String task) {
        try {
            countDownLatch.countDown();
            TimeUnit.SECONDS.sleep(1); // 模拟网络延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
//        2025-02-26 17:57:29.102Processed task: Task 89 in thread: VirtualThread[#123]/runnable@ForkJoinPool-1-worker-15
        System.out.println(TimeUtil.nowStrSSS()+"Processed task: " + task + " in thread: " + Thread.currentThread());
    }
    public static int size=1000;
    public static CountDownLatch countDownLatch=new CountDownLatch(size);
    public static void main(String[] args) throws InterruptedException {
        var begin=System.currentTimeMillis();
        
        var executor=getVirtualExecutor(10000);
        // 提交任务
        for (int i = 0; i < size; i++) {
            int finalI = i;
            executor.submit(() -> processTask("Task " + finalI));
        }
        System.out.println(TimeUtil.nowStrSSS()+"--------------------------------");
//        17:00:09.675
//        17:00:33.915
        countDownLatch.await();
        var end=System.currentTimeMillis();
        System.out.println("共耗时:"+(end-begin));
        executor.shutdown();// 关闭线程池
    }
}
